import 'package:flutter/material.dart';
import 'package:flutter_flux/flutter_flux.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:freemusic/components/LyricPanel.dart';
import 'package:freemusic/components/PlayListBottomSheet.dart';
import 'package:freemusic/model/AbstractSong.dart';
import 'package:freemusic/services/SongServices.dart';
import 'package:freemusic/stores/PlayerStores.dart';
import 'package:freemusic/utils/Util.dart';

class PlayPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return PlayPageState();
  }
}

class PlayPageState extends State<PlayPage> with StoreWatcherMixin<PlayPage> {
  PlayerStore _playerStore;
  SongServices _songServices = SongServices.getInstace();
  Duration timeLength = Duration(milliseconds: 0);

  @override
  void initState() {
    super.initState();
    _playerStore = listenToStore(playerStoreToken);
  }

  String _formatDuration(int duration){
    return duration < 10 ? "0$duration" : "$duration";
  }

  _buildSlider(Duration position, Duration total) {
    double sliderValue;
    String startTime;
    String endTime;
    if (total == null) {
      total = Duration(milliseconds: 0);
      sliderValue = 0;
      startTime = "00:00";
      endTime = "00:00";
    } else {
      sliderValue = position.inMilliseconds / total.inMilliseconds;
      startTime = "${_formatDuration(position.inMinutes)}:${_formatDuration(position.inSeconds % 60)}";
      endTime = "${_formatDuration(total.inMinutes)}:${_formatDuration(total.inSeconds % 60)}";
    }

    if (sliderValue > 1.0) {
      sliderValue = 1.0;
    }
    if (sliderValue.isNaN) {
      sliderValue = 0.0;
    }

    Color themeColor = Util.themeColor;

    return SliderTheme(
      data: SliderThemeData(
        activeTrackColor: themeColor,
        inactiveTrackColor: Color.fromRGBO(216, 30, 6, 0.3),
        thumbColor: themeColor,
      ),
      child: Row(
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(left: 8),
            child: Text("$startTime"),
          ),
          Expanded(
            child: Slider(
              value: sliderValue,
              onChanged: (value) {
                double positionValue = total.inMilliseconds * value;
                Duration position =
                    Duration(milliseconds: positionValue.toInt());
                _songServices.seek(position);
              },
            ),
          ),
          Container(
            margin: EdgeInsets.only(right: 8),
            child: Text("$endTime"),
          ),
        ],
      ),
    );
  }

  _renderPlaying(bool playing) {
    return playing
        ? Image.asset("images/zanting_p.png")
        : Image.asset("images/play_p.png");
  }

  void _showTempSongList() {
    showModalBottomSheet(
        context: context,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(12),
            topRight: Radius.circular(12),
          ),
        ),
        builder: (context) => PlayListBottomSheet());
  }

  Widget _renderSongImage(AbstractSong song) {
    if (song == null || song.img == null || song.img.isEmpty) {
      return Image.asset("images/nvhai.png");
    }
    return FadeInImage.assetNetwork(
      placeholder: "images/nvhai.png",
      image: song.img,
    );
  }

  String _renderPlayModel() {
    PlayModel playModel = _playerStore.playModel;
    if (playModel == PlayModel.single) {
      return "images/danqu.png";
    }
    if (playModel == PlayModel.shuffle) {
      return "images/suiji.png";
    }
    return "images/xunhuan.png";
  }

  void setTimeLength(Duration time){
    
  }
  @override
  Widget build(BuildContext context) {
    AbstractSong songInfo = _playerStore.current;
    setTimeLength(songInfo.timeLength);
    return Scaffold(
      body: Column(
        children: <Widget>[
          Container(
            height: MediaQuery.of(context).padding.top,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              IconButton(
                icon: Image.asset("images/houtui_1.png"),
                iconSize: 20.0,
                onPressed: () {
                  Navigator.pop(context);
                },
              ),
              IconButton(
                iconSize: 20.0,
                icon: Image.asset("images/yinleliebiao.png"),
                onPressed: this._showTempSongList,
              ),
            ],
          ),
          Container(
            decoration: BoxDecoration(
              boxShadow: [
                BoxShadow(
                    color: Color.fromRGBO(128, 128, 128, 1.0),
                    offset: Offset(0, 4),
                    blurRadius: 20)
              ],
            ),          
            height: 240,
            width: 240,
            margin: EdgeInsets.only(top: 20),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(12.0),
              child: this._renderSongImage(songInfo),
            ),
          ),
          Container(
            padding: EdgeInsets.all(20),
            child: Column(
              children: <Widget>[
                SingleChildScrollView(
                  scrollDirection: Axis.horizontal,
                  child: Text(
                    songInfo.songName == null ? "未播放歌曲" : songInfo.songName,
                    style: TextStyle(
                        color: Color.fromRGBO(20, 20, 20, 1), fontSize: 20),
                  ),
                ),
                Text(
                  songInfo.singerName == null ? "未播放歌曲" : songInfo.singerName,
                  style: TextStyle(
                    color: Color.fromRGBO(128, 128, 128, 1),
                  ),
                )
              ],
            ),
          ),
          StreamBuilder(
            builder: (_, AsyncSnapshot<Duration> snapshot) {
              return Column(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  LyricPanel(
                    songInfo.stringToLyric(),
                    height: 80.0,
                    position: snapshot.data,
                  ),
                  _buildSlider(snapshot.data, songInfo.timeLength),
                ],
              );
            },
            stream: _songServices.audioPlayer.onAudioPositionChanged,
            initialData: Duration(milliseconds: 0),
          ),
          Expanded(
            child: Container(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Button(
                    icon: this._renderPlayModel(),
                    onTap: () {
                      _songServices.changePlayModel();
                    },
                  ),
                  IconButton(
                    icon: Image.asset("images/prev_p.png"),
                    onPressed: () {
                      _songServices.prevSong();
                    },
                    iconSize: 48.0,
                  ),
                  IconButton(
                    icon: _renderPlaying(_playerStore.playing),
                    onPressed: () {
                      _songServices.changePlaying(!_playerStore.playing);
                    },
                    iconSize: 48.0,
                  ),
                  IconButton(
                    icon: Image.asset("images/next_p.png"),
                    onPressed: () {
                      _songServices.nextSong();
                    },
                    iconSize: 48.0,
                  ),
                  Button(
                    icon: "images/xiazai.png",
                    onTap: () {
                      _songServices.downloadSong(songInfo);
                    },
                  ),
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}

class Button extends StatelessWidget {
  final double _size = 32.0;
  final String icon;
  final GestureTapCallback onTap;

  Button({this.icon, this.onTap});

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(
        left: 12,
        right: 12,
      ),
      child: GestureDetector(
        child: Image.asset(
          this.icon,
          width: this._size,
        ),
        onTap: this.onTap,
      ),
    );
  }
}
